import {GameVar} from "./GameVar";
import {wxUtils} from "../wx/wxUtils";
import {WordsUtils} from "../utils/wordsUtils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class ReviveBoard extends cc.Component {

  @property(cc.Label)
  labelScore: cc.Label = null;
  @property(cc.Sprite)
  openDataContext: cc.Sprite = null;
  @property(cc.Node)
  btnShare: cc.Node = null
  @property(cc.Node)
  btnAd: cc.Node = null

  private texture: cc.Texture2D = new cc.Texture2D()

  // onLoad () {}

  start() {
  }

  setScore(value: number, rebornCount: number) {
    this.labelScore.string = value.toString()
    console.log('post message')
    if (rebornCount < 2) {
      this.btnShare.active = true
      this.btnAd.active = false
    } else {
      this.btnAd.active = true
      this.btnShare.active = false
    }
    wxUtils.postMessage({cmd: 'beKilled'})
    wxUtils.postMessage({cmd: 'showNext', score: value})
  }

  async onShare() {
    const res = await wxUtils.shareToFriends()
    if (res) {
      this.reborn()
    } else {
      WordsUtils.error('分享失败')
    }
  }

  private reborn() {
    GameVar.myHero.reborn();
    wxUtils.postMessage({cmd: 'enterGame'})
    this.node.parent.removeChild(this.node)
    wxUtils.hideMenuAd();
  }

  async onAd() {
    const result = await wxUtils.showVideoAd()
    if (result) {
      this.reborn()
    }
  }

  onPass() {
    this.node.emit('pass')
    wxUtils.postMessage({cmd: 'enterGame'})
    this.node.parent.removeChild(this.node)
    wxUtils.hideMenuAd();
  }

  update(dt) {
    this.texture.initWithElement(wxUtils.getSharedCanvas());
    this.texture.handleLoadedTexture();
    this.openDataContext.spriteFrame = new cc.SpriteFrame(this.texture)
  }
}

